#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: lonewolf
# Date: 2013-09-25 09:58:52
#
import re
import os
import shutil
import json
import time

js_path="/Users/lonewolf/Public/dev/web/html5/tools/js_api_build/api.txt"

snippetTemplate = """<snippet>
    <content><![CDATA[$content]]></content>
    <tabTrigger>$trigger</tabTrigger>
    <scope>source.js</scope>
    <description>$desc</description>
</snippet>
"""

# 保存的目录
SAVE_DIR="js_api"

        
def parseJs(file,saveDir):
    completionsList=[]
    filename=os.path.split(file)[1]
    filename=os.path.splitext(filename)[0]
    f=open(file,"r")
    lineNum=0
    globalDir=os.path.join(saveDir,"global")
    while True:
        line=f.readline()
        if line:
            lineNum+=1
            # 全局常量
            m=re.match("^(\w+);",line)
            if m:
                handleProp(globalDir,"",m.group(1))
                continue
            # 全局函数
            m=re.match("^function\s+(\w+)\s*\((.*)\)",line)
            if m:
                func=m.group(1)
                classname=""
                d=globalDir
                fstr="Array,Date,Number,String"
                if fstr.find(func)!=-1:
                    classname=func
                    d=saveDir
                handleFunction(d,classname,m.group(1),m.group(2))
                continue
            # static prop
            m=re.match("^(\w+)\.(\w+);",line)
            if m:
                handleProp(saveDir,m.group(1),m.group(1)+"."+m.group(2))
                continue
            # static func
            m=re.match("^(\w+)\.(\w+)\s*=\s*function\s*\((.*)\)",line)
            if m:
                handleFunction(saveDir,m.group(1),m.group(1)+"."+m.group(2),m.group(3))
                continue
            # class func
            m=re.match("^(\w+)\.prototype\.(\w+)\s*=\s*function\s*\((.*)\)",line)
            if m:
                handleFunction(saveDir,m.group(1),m.group(2),m.group(3))
                continue
            # class prop
            m=re.match("^(\w+)\.prototype\.(\w+)\s*=\s*",line)
            if m:
                handleProp(saveDir,m.group(1),m.group(2))
                continue
        else:
            break
    f.close()

# 处理方法,生成snappit文件
def handleFunction(saveDir,classname,funcName,params,childClass=None):
    arr=handleParams(params)
    content=funcName+"(%s)"%(arr[1])
    trigger=funcName+"(%s)"%(arr[0])
    template=snippetTemplate.replace("$content",content)
    template=template.replace("$trigger",trigger)
    if childClass:
        template=template.replace("$desc",childClass)
    else:
        template=template.replace("$desc",classname)
    # 文件名
    a=""
    if arr[0]!="":
        args=arr[0].split(",")
        for i in range(0,len(args)):
            args[i]=re.sub("\W","",args[i])
        a="_".join(args)
        a="_"+a
    saveName=funcName+a+".sublime-snippet"
    if classname==funcName:
        saveName="Class_"+saveName
        # print(funcName+params);
    # print saveName
    # 建立类对应的目录
    newSaveDir=os.path.join(saveDir,classname)
    if childClass:
        newSaveDir=os.path.join(newSaveDir,childClass)
    if not os.path.exists(newSaveDir):
        os.makedirs(newSaveDir)
    savePath=os.path.join(newSaveDir,saveName)
    f=open(savePath, "w+")
    f.write(template)
    f.close()

# 处理属性,生成snappit文件
def handleProp(saveDir,classname,propName):
    template=snippetTemplate.replace("$content",propName)
    template=template.replace("$trigger",propName)
    template=template.replace("$desc",classname)
    # 文件名
    saveName=propName+".sublime-snippet"
    # print saveName
    # 建立类对应的目录
    saveDir=os.path.join(saveDir,classname)
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)
    savePath=os.path.join(saveDir,saveName)
    f=open(savePath, "w+")
    f.write(template)
    f.close()

# 处理函数变量
def handleParams(params):
    args=[]
    for item in params.split(","):
        str1=re.sub("\s","",item)
        if str1!="":
            args.append(str1)
    args2=[]
    for i in range(0,len(args)):
        args2.append("${%d:%s}"%(i+1,args[i]))
    a1=", ".join(args)
    a2=", ".join(args2)
    return [a1,a2]


# 先删除保存目录下的文件，但不删除保存目录root
def deleteFiles(path,root):
    if os.path.isfile(path):
        try:
            os.remove(path)
        except Exception, e:
            pass
    elif os.path.isdir(path):
        for item in os.listdir(path):
            itemsrc=os.path.join(path,item)
            deleteFiles(itemsrc,root)
        if path!=root:            
            try:
                os.rmdir(path)
            except Exception, e:
                pass

deleteFiles(SAVE_DIR,SAVE_DIR)
parseJs(js_path,SAVE_DIR)